﻿@using Newtouch.Infrastructure;
@{
    ViewBag.title = "医嘱执行";
    Layout = "~/Views/Shared/_Index.cshtml";
    //欠费医嘱执行开关
    var ISOpenqfswith = (ViewBag.isqfswith);
    var reportUrl = Newtouch.Core.Common.Utils.ConfigurationHelper.GetAppConfigValue("ReportUrl");
    var reportSystemCode = Newtouch.Core.Common.Utils.ConfigurationHelper.GetAppConfigValue("ReportSystemCode");
    var curOpr = Newtouch.Common.Operator.OperatorProvider.GetCurrent();
}
<script src="@SiteUrl.GetStaticResourceScriptUrl("~/js/wdtree/tree.js")"></script>
<link href="@SiteUrl.GetStaticResourceScriptUrl("~/js/wdtree/tree.css")" rel="stylesheet" />
<style>
    .dv-left {
        width: 200px;
        float: left;
    }

    .dv-left-tree {
        overflow-y: auto;
        border-radius: 4px;
        background: white;
    }

    .dv-left-title {
        padding: 6px 10px;
        border-bottom: 1px solid transparent;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
        border-color: #ddd;
        background-color: white;
    }

    .dv-right {
        float: left;
        margin-left: 5px;
    }

    .dv-right-order {
        width: 100%;
    }

    .dv-grid {
        width: 100%;
    }
</style>
<div class="dv-body">
    <div class="dv-left">
        <div class="dv-left-title">患者列表</div>
        <div class="dv-left-tree" id="BqTreeList"></div>
    </div>
    <div class="dv-right">
        <div class="dv-right-order">
            <div class="topPanel">
                <div class="toolbar" style="float:left; padding-left:45px;">
                    <table>
                        <tr>
                            <td class="formTitle"> 执行日期：</td>
                            <td class="formValue">
                                <input id="txt_zxrq" type="text" class="form-control input-wdatepicker" style="width:70%; height:35%; float:left;"
                                       onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd' })"
                                       onfocus="WdatePicker({ dateFmt: 'yyyy-MM-dd', onpicked: function () { RefreshOrder() } })" value="@DateTime.Now.ToString("yyyy-MM-dd ")" />
                            </td>
                            <td class="formTitle">执行时间：</td>
                            <td class="formValue">
                                <input id="txt_yzxsj" type="text" class="form-control input-wdatepicker" style="width:70%; height:35%; float:left;"
                                       onclick="WdatePicker({ dateFmt: 'HH:mm:ss' })"
                                       onfocus="WdatePicker({ dateFmt: 'HH:mm:ss' })" value="@DateTime.Now.ToString("HH:mm:ss")" />
                            </td>
                            @*<td>
            <input type="button" id="btn_search" class="btn btn-primary" value="查询预执行医嘱" />
        </td>*@
                        </tr>
                    </table>
                </div>
                <div style="float:right; padding-right:15px">
                    <div class="btn-group">
                        <a class="btn btn-primary" onclick="RefreshOrder()"><span class="fa fa-refresh"></span></a>
                    </div>
                    <div class="btn-group">
                        <a id="ExecutionChecked" class="btn btn-primary" onclick="ExecutionChecked()">
                            <i class="fa fa-pencil-square-o"></i>执行当前
                        </a>
                    </div>
                    <div class="btn-group">
                        <a id="ExecutionTemporary" class="btn btn-primary" onclick="ExecutionOrders(@Html.Raw(((int)EnumYzxz.Ls).ToString()))">
                            <i class="fa fa-pencil-square-o"></i>执行临时
                        </a>
                        @*<a id="ExecutionTemporary" class="btn btn-primary" onclick="ExecutionOrders(1)">
                                <i class="fa fa-pencil-square-o"></i>执行临时
                            </a>*@
                    </div>
                    <div class="btn-group">
                        <a id="ExecutionLong" class="btn btn-primary" onclick="ExecutionOrders(@Html.Raw(((int)EnumYzxz.Cq).ToString()))">
                            <i class="fa fa-pencil-square-o"></i>执行长期
                        </a>
                        @*<a id="ExecutionLong" class="btn btn-primary" onclick="ExecutionOrders(2)">
                                <i class="fa fa-pencil-square-o"></i>执行长期
                            </a>*@
                    </div>
                    <div class="btn-group">
                        <a id="ExecutionAll" class="btn btn-primary" onclick="ExecutionOrders(0)">
                            <i class="fa fa-pencil-square-o"></i>执行全部
                        </a>
                    </div>
                </div>
            </div>
            <div class="gridPanel">
                <table id="gridList"></table>
                <div id="gridPager"></div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var yjjzhmsg = "";
    $(".dv-body").height($(window).height());
    $(".dv-body").width($(window).width());
    var rightWidth = $(".Newtouch_iframe", parent.document).width() - $(".dv-left").width() - 25;
    $(".dv-right").width(rightWidth);
    $(".dv-left-tree").height($(window).height() - 70);

    $(function () {
        $(window).resize(function () {//浏览器窗口调整大小时重新计算宽高
            $(".dv-body").height($(window).height());
            $(".dv-body").width($(window).width());
        });
        var zyhtimes = $.request("data");
        var currentobj = JSON.parse(sessionStorage.getItem('currentpatobj'));//护士患者一览
        if (currentobj) {
            zyhtimes = currentobj.zyh + ',';
            sessionStorage.removeItem("currentpatobj");
        }
        $(window).resize(function () {//浏览器窗口调整大小时重新计算宽高
            $(".dv-body").height($(window).height());
            $(".dv-body").width($(window).width());
        });
        allbtn();
        $('#gridList').jqGrid("clearGridData");
        //$('#gridList').newtouchLocalDataGrid(null, orderList);
        getBqTreeList(zyhtimes);
        gridList(zyhtimes);
    });

    function getBqTreeList(zyhtimes) {

        $("#BqTreeList").treeview({
            height: $(".dv-body").height() - 40,
            slimscroll: false,
            showcheck: true,
            url: "/NurseManage/OrderExecution/GetPatWardTree",
            param: { aa: zyhtimes, zxsj: $('#txt_zxrq').val() },
            oncheckboxclick: function (item, s) {

                getOrderExecutionList(item, s);
            }
        });

    }

    function getOrderExecutionList(item, s) {
        var patlist = $("#BqTreeList").getCheckedNodeObjArray();
        var patlistFath = "";
        yjjzhmsg = "";
        var patzyh = "";

        //当前选中父节点
        var len = 0;
        var single = 0; //是否单个子节点

        if (item != null && item.Ex1 == "p") {
            patlistFath = item.ChildNodes;
            len = patlistFath.length;
        }
        else if (item != null && item.Ex1 == "c") {
            patlistFath = item;
            len = 1;
            single = 1;
        }

        //选中节点
        for (var i = 0; i < patlist.length; i++) {
            if (patlist[i].Ex1 == "c") {
                patzyh += patlist[i].value + ",";
            }
        }

        if (s == 1) {
            if (single == 0) {
                for (var j = 0; j < len; j++) {
                    if (patlistFath[j].Ex1 == "c") {
                        patzyh += patlistFath[j].value + ",";
                    }
                }
            }
            else if (patlistFath.Ex1 == "c") {
                patzyh += patlistFath.value;
            }
        }
        else if (s == 0) {
            if (single == 0) {
                for (var j = 0; j < len; j++) {
                    if (patlistFath[j].Ex1 == "c" && patlistFath[j].checkstate == 1) {
                        patzyh = patzyh.replace(patlistFath[j].value + ",", "");
                    }
                }
            }
            else if (patlistFath.Ex1 == "c") {
                patzyh = patzyh.replace(patlistFath.value + ",", "");
            }

        }

        //settetime();//刷新时间
        //$('#txt_yzxsj').val(getNowTime());//每次查询获取最新时分秒

        //$('#gridList').jqGrid("clearGridData");
        $('#gridList').jqGrid('setGridParam', {
            postData: {
                patList: patzyh, zxsj: $('#txt_zxrq').val() + " " + $('#txt_yzxsj').val()
            }
        }).trigger("reloadGrid");
        if ("@ISOpenqfswith" == "ON" && patzyh)
        {
            $.najax({
                type: "POST",
                url: "/PatientList/PatYjjWarn",
                data: { patlist: patzyh },
                dataType: "json",
                async: false,
                success: function (ajaxresp) {
                    UnExecutionList = [];
                    WarmList = [];
                    //$.each(ajaxresp, function () {
                    //    if(this.zhsy<=this.bje &&this.zhsy>0)
                    //    {
                    //        $.modalAlert("住院号:" + this.zyh + "预交账户余额已达到限额,请提醒患者充值", 'warning');
                    //        WarmList.push(this.zyh);
                    //    } 
                    //    else if (this.zhsy<=0)//&& this.zhye>0
                    //    {
                    //        yjjzhmsg = "住院号:" + this.zyh + "预交账户已欠费,不能产生计费,需先充值预交账户";
                    //        $.modalAlert(yjjzhmsg, 'warning');
                    //        UnExecutionList.push(this.zyh);
                    //    }
                    //    return;
                    //});
                }
            });
        }
    }

    function settetime() {

        var date = new Date();
        var dates = date.getHours();
        var datef = date.getMinutes();
        if (datef < 9) {
            datef = "0" + datef;
        }
        var datem = date.getSeconds();
        if (datem < 9) {
            datem = "0" + datem;
        }
        var tetime = dates + ":" + datef + ":" + datem;
        //console.log(tetime);
        $('#txt_yzxsj').val(tetime);
    }

    function getOrderListByPatId(patid) {
        $('#gridList').jqGrid("clearGridData");
        $('#gridList').newtouchLocalDataGrid(null, orderList);
    }

    //级联选中所有子节点
    function checkAllSon(node) {
        $('#BqTreeList').treeview('checkNode', node.nodeId, { silent: true });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                checkAllSon(node.nodes[i]);
            }
        }
    }
    //级联取消所有子节点
    function uncheckAllSon(node) {
        $('#BqTreeList').treeview('uncheckNode', node.nodeId, { silent: true });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                uncheckAllSon(node.nodes[i]);
            }
        }
    }
    var checkTrigger = false;
    var list = new Array();
    var liststu = false;
    var j = 0;

    getNowTime = function () {
        let dateTime
        let yy = new Date().getFullYear()
        let mm = new Date().getMonth() + 1
        let dd = new Date().getDate()
        let hh = new Date().getHours()
        let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
        let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
        dateTime = hh + ':' + mf + ':' + ss;

        console.log(dateTime)
        return dateTime
    }

    function gridList(patzyh) {
        var $gridList = $("#gridList");
        $gridList.dataGrid({
            multiselect: true,
            postData: { patList: patzyh, zxsj: $('#txt_zxrq').val() },
            url: "/NurseManage/OrderExecution/GetGridJson",
            height: $(window).height() - 125,
            colModel: [
                { label: '医嘱ID', name: 'yzid', align: 'center', width: 50, key: true, hidden: true },
                { label: '住院号', name: 'zyh', align: 'center', width: 50, hidden: true },
                { label: '患者姓名', name: 'hzxm', align: 'center', width: 60 },
                { label: '医嘱组号', name: 'zh', align: 'center', width: 50, formatter: function (val) { if (val != null) return val; else return ""; } },
                { label: 'zh1', name: 'zh1', align: 'center', width: 70, hidden:true, formatter: function (val) { if (val != null) return val; else return ""; } },
                { label: '医嘱项目', name: 'xmmc', align: 'left', width: 150 },
                {
                    label: '医嘱类型', name: 'yzlx', align: 'center', width: 60, formatter: function (val, option, row) {
                        return $.enum.getDescByValue("EnumYzlx", row.yzlx);
                    }
                },
                { label: '剂量', name: 'yzjl', align: 'center', width: 40 },
                { label: '用法', name: 'yfmc', align: 'center', width: 30 },
                { label: '频次', name: 'yzpcmc', align: 'center', width: 30 },
                { label: 'yzlx', name: 'yzlx', align: 'center', hidden: true },
                { label: 'isjf', name: 'isjf', align: 'center', hidden: true },
                { label: 'zh1', name: 'zh1', align: 'center', hidden: true },
                { label: 'yfztbs', name: 'yfztbs', align: 'center', hidden: true },
                { label: '医嘱性质', name: 'yzxzsm', align: 'center', width: 60 },
                { label: '收费项目单价', name: 'dj', align: 'center', width: 100, hidden: true },
                { label: '医嘱', name: 'yznr', align: 'left', width: 300 },
                { label: '开始时间', name: 'kssj', align: 'center', width: 110, formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' } },
                { label: '最后执行时间', name: 'zxsj', align: 'center', width: 110, formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' } },
                { label: '停止/作废时间', name: 'tzsj', align: 'center', width: 110, formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' } },
                {
                     label: '药品来源', name: 'yply', align: 'center', width: 50, formatter: function (val) {
                         return $.enum.getDescByValue("EnumYply", val);
                     }
                 },
                { label: '精麻', name: 'yztagName', align: 'center', width: 50 },
                 {
                     label: '是否计费', name: 'isjf', align: 'center', width: 50, formatter: function (val) {
                         return $.enum.getDescByValue("EnumSF", val);
                     }
                 },
                { label: '审核者', name: 'shr', align: 'center', width: 70 },
                { label: '执行者', name: 'zxr', align: 'center', width: 70, hidden: true },
                { label: '医嘱性质编码', name: 'yzxz', align: 'center', width: 70, hidden: true },

            ],
            pager: "#gridPager",
            sortname: 'kssj desc,zyh,yzlx,zh',
            viewrecords: true,
            multiselect: true,
            onSelectRow: function (rowIndex, s) {
                if (!checkTrigger) {
                    var len = 0;
                    var rowData = $("#gridList").jqGrid('getRowData', rowIndex);
                    var ids = $("#gridList").jqGrid('getRowData_AllLine');
                    liststu = s; //同步状态
                    if (rowData.zh1!="") {
                        for (var i = 0; i < ids.length; i++) {
                            if (ids[i].zh1 === rowData.zh1 && ids[i].zh1 !== "") {
                                if (s === true) {
                                    if (rowIndex !== ids[i].yzid) {
                                        list[len] = ids[i].yzid;
                                        len += 1;
                                    }
                                }
                                else {
                                    if (rowIndex !== ids[i].yzid) {
                                        list[len] = ids[i].yzid;
                                        len += 1;
                                    }
                                }
                            }
                        }
                    }
                    else {
                        for (var i = 0; i < ids.length; i++) {
                            if (ids[i].zh === rowData.zh && ids[i].zh !== "") {
                                if (s === true) {
                                    if (rowIndex !== ids[i].yzid) {
                                        list[len] = ids[i].yzid;
                                        len += 1;
                                    }
                                }
                                else {
                                    if (rowIndex !== ids[i].yzid) {
                                        list[len] = ids[i].yzid;
                                        len += 1;
                                    }
                                }
                            }
                        }
                    }

                    checkTrigger = true;
                }

                if (list.length > 0) {

                    for (j; j < list.length; j++) {
                        if (liststu) //同组选中
                        {
                            j = j + 1;
                            $("#gridList").jqGrid("setSelection", list[j - 1], true);

                        }
                        else { //同组取消选中
                            //j = j + 1;
                            $("#gridList").jqGrid("setSelection", list[j], false);      //取消不触发onselectrow
                        }

                    }
                }

                j = 0;
                checkTrigger = false;
                list = new Array();
                liststu = false;
            }
        });
    }
    //刷新医嘱
    function RefreshOrder() {
        getBqTreeList("");
        $('#gridList').jqGrid("clearGridData");
        getOrderExecutionList(null, null);
        allbtn();
        //$("#txt_yzxsj").val(new Date().format("hh:mm:ss"));
        //$("#txt_yzxsj").val(getNowTime());
    }
    //禁用所有按钮
    function allbtndisabled() {
        $('#ExecutionChecked').attr("disabled", true);
        $('#ExecutionTemporary').attr("disabled", true);
        $('#ExecutionLong').attr("disabled", true);
        $('#ExecutionAll').attr("disabled", true);
    }
    //启用所有按钮
    function allbtn() {
        $('#ExecutionChecked').attr("disabled", false);
        $('#ExecutionTemporary').attr("disabled", false);
        $('#ExecutionLong').attr("disabled", false);
        $('#ExecutionAll').attr("disabled", false);
    }
    //执行当前
    var UnExecutionList = [];
    var WarmList = [];
    function ExecutionChecked() {
        //allbtndisabled();
        var selPatTrees = $("#BqTreeList").getCheckedNodeObjArray();
        if (selPatTrees == null || selPatTrees.length < 1) {
            $.modalAlert("请先选中需执行的患者", 'warning');
            allbtn();
            return;
        }
        var patzyh = "";
        for (var i = 0; i < selPatTrees.length; i++) {
            if (selPatTrees[i].Ex1 === "c") {
                patzyh += selPatTrees[i].value + ",";
                //预交金超出限额无法执行
                //if (UnExecutionList.indexOf(selPatTrees[i].value) != -1) {
                //    $.modalAlert("预交账户已欠费,不能产生计费,需先充值预交账户", 'warning');
                //    return;
                //}
            }
        }
        if (patzyh === "") {
            $.modalAlert("请先选中需执行的患者", 'warning');
            allbtn();
            return;
        }
        if (yjjzhmsg)
        {
            $.modalAlert(yjjzhmsg, 'warning');
            allbtn();
            return;
        }
        var strYZID = [];
        var selRowIds = jQuery("#gridList").jqGrid("getGridParam", "selarrrow");//选中的id
        if (selRowIds == null || selRowIds.length === 0) {
            $.modalAlert("请先选中需执行的医嘱", 'warning');
            allbtn();
            return;
        }
        for (var i = 0; i < selRowIds.length; i++) {
            var rowData = $("#gridList").jqGrid('getRowData', selRowIds[i]);
            strYZID.push({
                zyh: rowData.zyh, yzid: rowData.yzid, yzxz: rowData.yzxz, yzlx: rowData.yzlx, dj: rowData.dj,
                zxsj: rowData.zxsj, ypmc: rowData.xmmc, zh: rowData.zh, zh1: rowData.zh1, isjf: rowData.isjf,
                yfztbs: rowData.yfztbs, yply: rowData.yply
            });
        }
        $.loading(true, "医嘱执行中，请稍后...");
        var Vzxsj = ctorzxsj();
       
        $.ajax({
            type: "POST",
            url: "/NurseManage/OrderExecution/submitOrderExecutionList",
            data: { patlist:patzyh,orderList: strYZID, Vzxsj: Vzxsj },
            dataType: "json",
            //async: false,
            success: function (ajaxresp) {
                var rtnobj = JSON.parse(ajaxresp.data);
                if (ajaxresp.state === "success") {
                    $.ajax({
                        type: "POST",
                        url: "/NurseManage/OrderExecution/pushApplicationform",
                        data: { orderList: strYZID },
                        dataType: "json",
                        async: false,
                        success: function (repjson) {

                        }
                    });
                    if (rtnobj.cnt > 0) {
                       
                        $.modalConfirm("执行成功，是否打印？",
                            function (flag) {
                                if (flag) {
                                    console.log($("#txt_zxrq").val());
                                    var uri = '@reportUrl' + "?tempCode=98" + "&systemCode=" + '@reportSystemCode' + "&yzh=" + "" + "&orgId=" + '@curOpr.OrganizeId' + "&lyxh=" + rtnobj.lyxh + "&zxrq=" + ctorzxsj();
                                    window.open(uri);
                                    //window.open("/ReportManage/Report/PrintYzYpReport?yzh=" + rtnobj.yzh + "&lyxh=" + rtnobj.lyxh + "&zxrq=" + rtnobj.zxrq, "height=500, width=1195,top=100, left=50, toolbar =no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no");
                                }
                            });
                    }
                    $.loading(false);
                    RefreshOrder();
                }
                else {
                    $.modalAlert(ajaxresp.message, 'warning');  
                    RefreshOrder();
                }
                //getOrderExecutionList(null, null);
            }
        });
    }

    function ctorzxsj() {
        var zxrq = $('#txt_zxrq').val();
        var yzzxsj = $('#txt_yzxsj').val();
        return $.getDate({ date: zxrq }) + " " + yzzxsj; //$.getTime().substring(11, 19);
    }
    //执行临时  长期  全部
    function ExecutionOrders(yzxz) {
        //allbtndisabled();
        var selPatTrees = $("#BqTreeList").getCheckedNodeObjArray();
        if (selPatTrees == null || selPatTrees.length < 1) {
            $.modalAlert("请先选中需执行的患者", 'warning');
            allbtn();
            return;
        }
        var patzyh = "";
        for (var i = 0; i < selPatTrees.length; i++) {
            if (selPatTrees[i].Ex1 === "c") {
                patzyh += selPatTrees[i].value + ",";
                //预交金超出限额无法执行
                //if (UnExecutionList.indexOf(selPatTrees[i].value) != -1) {
                //    $.modalAlert("预交账户已欠费,不能产生计费,需先充值预交账户", 'warning');
                //    return;
                //}
            }
        }
        if (patzyh === "") {
            $.modalAlert("请先选中需执行的患者", 'warning');
            allbtn();
            return;
        }
        if (yjjzhmsg) {
            $.modalAlert(yjjzhmsg, 'warning');
            allbtn();
            return;
        }
        var Vzxsj = ctorzxsj();
        $.loading(true, "医嘱执行中，请稍后...");
        $.ajax({
            type: "POST",
            url: "/NurseManage/OrderExecution/submitOrderExecutionListbyPat",
            data: { patlist: patzyh, yzxz: yzxz, Vzxsj: Vzxsj },
            dataType: "json",
            success: function (ajaxresp) {
                if (ajaxresp.state === "success") {
                    var rtnobj = JSON.parse(ajaxresp.data);
                    if (rtnobj.cnt > 0) {
                        $.modalConfirm("执行成功，是否打印？",
                            function (flag) {
                                if (flag) {
                                    var lyxh = jQuery.parseJSON(ajaxresp.data).lyxh;;
                                    window.open("/ReportManage/Report/PrintYzYpReport?yzh=&lyxh=" + lyxh + "&zxrq=" + Vzxsj, "height=500, width=1195,top=100, left=50, toolbar =no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no");
                                }
                            });
                    }
                    $.loading(false);
                    RefreshOrder();
                }
                else {
                    $.modalAlert(ajaxresp.message, 'warning');
                    RefreshOrder();
                }
                //getOrderExecutionList(null, null);
            }
        });
    }
         //无操作刷新页面
        //this.interval = setInterval(() => {
        //    RefreshOrder()
        //}, 3000);

    var maxTime = 60*1; // seconds
    var time = maxTime;
    $('body').on('keydown mousemove mousedown', function(e) {
        time = maxTime; // reset
    });
    //var intervalId = setInterval(function() {
    //    time--;
    //    if (time <= 0) {
    //        ShowInvalidLoginMessage();
    //        clearInterval(intervalId);
    //    }
    //}, 1000)
    function ShowInvalidLoginMessage() {
        RefreshOrder()
    }
</script>